﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace YTCMS.Core
{
    public  class QueryHelper
    {
        public static IQueryable<T> ExpreessionOrderBy<T>(IQueryable<T> source, string propertyStr, string orderBy) where T : class
        {
            ParameterExpression param = Expression.Parameter(typeof(T), "c");
            PropertyInfo property = typeof(T).GetProperty(propertyStr);
            Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
            LambdaExpression le = Expression.Lambda(propertyAccessExpression, param);
            Type type = typeof(T);
            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), orderBy, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(le));
            return source.Provider.CreateQuery<T>(resultExp);
        }

        public static IQueryable<T> WhereIf<T>(IQueryable<T> source, Expression<Func<T, bool>> predicate, bool condition)
        {
            return condition ? source.Where(predicate) : source;
        }
    }
}
